<template>
  <div class="activity-edit-page">
    <div class="page-container">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item><router-link to="/">首页</router-link></el-breadcrumb-item>
        <el-breadcrumb-item><router-link to="/activity-list">活动列表</router-link></el-breadcrumb-item>
        <el-breadcrumb-item>{{ isEdit ? '编辑活动' : '创建活动' }}</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="card">
        <h1 class="page-title">{{ isEdit ? '编辑活动' : '创建活动' }}</h1>
        
        <!-- 加载状态 -->
        <el-skeleton v-if="loading" animated class="skeleton-container">
          <template #template>
            <el-skeleton-item variant="text" style="width: 30%" />
            <el-skeleton-item variant="text" style="width: 100%" />
            <el-skeleton-item variant="text" style="width: 100%" />
            <el-skeleton-item variant="text" style="width: 100%" />
            <el-skeleton-item variant="text" style="width: 100%" />
          </template>
        </el-skeleton>
        
        <!-- 错误状态 -->
        <div v-else-if="error" class="error-container">
          <el-empty description="加载失败，请稍后重试" />
          <el-button type="primary" @click="handleRetry">重试</el-button>
        </div>
        
        <el-form
          ref="activityFormRef"
          :model="activityForm"
          :rules="activityRules"
          label-width="120px"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <h2 class="section-title">基本信息</h2>
            
            <el-form-item label="活动标题" prop="title">
              <el-input
                v-model="activityForm.title"
                placeholder="请输入活动标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item label="活动分类" prop="categoryId">
              <el-select
                v-model="activityForm.categoryId"
                placeholder="请选择活动分类"
                clearable
              >
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="活动地点" prop="location">
              <el-input
                v-model="activityForm.location"
                placeholder="请输入活动地点"
                maxlength="200"
              />
            </el-form-item>
            
            <el-form-item label="活动封面">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="activityForm.coverUrl" :src="activityForm.coverUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">支持 jpg, png, gif 格式，大小不超过 2MB</div>
            </el-form-item>
          </div>
          
          <!-- 时间设置 -->
          <div class="form-section">
            <h2 class="section-title">时间设置</h2>
            
            <el-form-item label="活动开始时间" prop="startTime">
              <el-date-picker
                v-model="activityForm.startTime"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="活动结束时间" prop="endTime">
              <el-date-picker
                v-model="activityForm.endTime"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="报名开始时间" prop="registrationStartTime">
              <el-date-picker
                v-model="activityForm.registrationStartTime"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="报名结束时间" prop="registrationEndTime">
              <el-date-picker
                v-model="activityForm.registrationEndTime"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
              />
            </el-form-item>
          </div>
          
          <!-- 参与设置 -->
          <div class="form-section">
            <h2 class="section-title">参与设置</h2>
            
            <el-form-item label="最大参与人数" prop="maxParticipants">
              <el-input-number
                v-model="activityForm.maxParticipants"
                :min="1"
                :max="9999"
                :step="1"
                placeholder="不填表示不限"
              />
              <div class="form-tip">不填表示不限人数</div>
            </el-form-item>
            
            <el-form-item label="是否需要审核">
              <el-switch v-model="activityForm.needApproval" />
              <div class="form-tip">开启后，用户报名需要管理员审核通过</div>
            </el-form-item>
            
            <el-form-item label="活动费用" prop="fee">
              <el-input-number
                v-model="activityForm.fee"
                :min="0"
                :step="0.01"
                :precision="2"
                placeholder="免费活动请填0"
              />
              <span class="currency-unit">元</span>
            </el-form-item>
          </div>
          
          <!-- 活动详情 -->
          <div class="form-section">
            <h2 class="section-title">活动详情</h2>
            
            <el-form-item label="活动描述" prop="description">
              <div class="editor-container">
                <!-- 这里使用简单的富文本编辑器，实际项目中可以使用更完整的编辑器 -->
                <el-input
                  v-model="activityForm.description"
                  type="textarea"
                  :rows="10"
                  placeholder="请输入活动详细描述（支持HTML）"
                />
                <div class="editor-tip">支持基本HTML标签，如 p, br, strong, em, ul, ol, li, img, a 等</div>
              </div>
            </el-form-item>
            
            <el-form-item label="活动须知" prop="notes">
              <el-input
                v-model="activityForm.notes"
                type="textarea"
                :rows="4"
                placeholder="请输入活动须知"
              />
            </el-form-item>
          </div>
          
          <!-- 状态设置 -->
          <div v-if="isEdit" class="form-section">
            <h2 class="section-title">状态设置</h2>
            
            <el-form-item label="活动状态" prop="status">
              <el-select
                v-model="activityForm.status"
                placeholder="请选择活动状态"
                clearable
              >
                <el-option label="草稿" value="DRAFT" />
                <el-option label="已发布" value="PUBLISHED" />
                <el-option label="已取消" value="CANCELLED" />
              </el-select>
            </el-form-item>
            
            <el-form-item v-if="getMappedStatus(activityForm.status) === 'CANCELLED'" label="取消原因">
              <el-input
                v-model="activityForm.cancelReason"
                type="textarea"
                :rows="3"
                placeholder="请输入取消活动的原因"
              />
            </el-form-item>
          </div>
          
          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" :loading="submitting" @click="handleSubmit('PUBLISHED')">
              发布活动
            </el-button>
            <el-button type="success" :loading="submitting" @click="handleSubmit('DRAFT')">
              保存草稿
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getActivityDetail, createActivity, updateActivity } from '../api/activity'
import { getCategoryList } from '../api/category'
import { mapStatusToBackend, mapStatusToFrontend } from '../utils/common'

export default {
  name: 'ActivityEdit',
  components: {
    Plus
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const activityFormRef = ref(null)
    const submitting = ref(false)
    const loading = ref(false)
    const error = ref(null)
    const categories = ref([])
    
    // 判断是编辑还是创建
    const isEdit = computed(() => {
      return !!route.params.id
    })
    
    // 上传URL（实际项目中应该从环境变量或配置中获取）
    const uploadUrl = '/api/upload/image'
    
    // 活动表单
    const activityForm = ref({
      title: '',
      categoryId: null,
      location: '',
      coverUrl: '',
      startTime: '',
      endTime: '',
      registrationStartTime: '',
      registrationEndTime: '',
      maxParticipants: null,
      needApproval: false,
      fee: 0,
      description: '',
      notes: '',
      status: 'DRAFT',
      cancelReason: ''
    })
    
    // 表单验证规则
    const activityRules = {
      title: [
        { required: true, message: '请输入活动标题', trigger: 'blur' },
        { min: 5, max: 100, message: '标题长度在5-100个字符', trigger: 'blur' }
      ],
      categoryId: [
        { required: true, message: '请选择活动分类', trigger: 'change' }
      ],
      location: [
        { required: true, message: '请输入活动地点', trigger: 'blur' },
        { max: 200, message: '地点不能超过200个字符', trigger: 'blur' }
      ],
      startTime: [
        { required: true, message: '请选择活动开始时间', trigger: 'change' }
      ],
      endTime: [
        { required: true, message: '请选择活动结束时间', trigger: 'change' },
        {
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('请选择活动结束时间'))
            }
            if (activityForm.value.startTime && new Date(value) <= new Date(activityForm.value.startTime)) {
              return callback(new Error('结束时间必须晚于开始时间'))
            }
            callback()
          },
          trigger: 'change'
        }
      ],
      registrationStartTime: [
        { required: true, message: '请选择报名开始时间', trigger: 'change' },
        {
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('请选择报名开始时间'))
            }
            if (activityForm.value.startTime && new Date(value) >= new Date(activityForm.value.startTime)) {
              return callback(new Error('报名开始时间必须早于活动开始时间'))
            }
            callback()
          },
          trigger: 'change'
        }
      ],
      registrationEndTime: [
        { required: true, message: '请选择报名结束时间', trigger: 'change' },
        {
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('请选择报名结束时间'))
            }
            if (activityForm.value.startTime && new Date(value) >= new Date(activityForm.value.startTime)) {
              return callback(new Error('报名结束时间必须早于活动开始时间'))
            }
            if (activityForm.value.registrationStartTime && new Date(value) <= new Date(activityForm.value.registrationStartTime)) {
              return callback(new Error('报名结束时间必须晚于报名开始时间'))
            }
            callback()
          },
          trigger: 'change'
        }
      ],
      description: [
        { required: true, message: '请输入活动描述', trigger: 'blur' },
        { min: 20, message: '活动描述至少20个字符', trigger: 'blur' }
      ],
      notes: [
        { max: 500, message: '活动须知不能超过500个字符', trigger: 'blur' }
      ]
    }
    
    // 获取活动详情（编辑模式）
    const fetchActivityDetail = async () => {
      if (!isEdit.value) return
      
      try {
        loading.value = true
        error.value = null
        
        // 直接调用API获取活动详情
        const response = await getActivityDetail(route.params.id)
        const activity = response.data
        
        // 填充表单数据
        activityForm.value = {
          id: activity.id,
          title: activity.title,
          categoryId: activity.categoryId,
          location: activity.location,
          coverUrl: activity.coverUrl,
          startTime: activity.startTime,
          endTime: activity.endTime,
          registrationStartTime: activity.registrationStartTime,
          registrationEndTime: activity.registrationEndTime,
          maxParticipants: activity.maxParticipants,
          needApproval: activity.needApproval || false,
          fee: activity.fee || 0,
          description: activity.description,
          notes: activity.notes || '',
          status: mapStatusToFrontend(activity.status),
          cancelReason: activity.cancelReason || ''
        }
      } catch (err) {
        error.value = err
        ElMessage.error('获取活动详情失败')
      } finally {
        loading.value = false
      }
    }
    
    // 重试加载
    const handleRetry = async () => {
      error.value = null
      await initializePage()
    }
    
    // 提交表单
    const handleSubmit = async (targetStatus) => {
      if (!activityFormRef.value) return
      
      try {
        await activityFormRef.value.validate()
        submitting.value = true
        
        const formData = {
          ...activityForm.value,
          status: mapStatusToBackend(targetStatus)
        }
        
        if (isEdit.value) {
          // 直接调用API更新活动
          await updateActivity(formData)
          ElMessage.success('活动更新成功')
        } else {
          // 直接调用API创建活动
          await createActivity(formData)
          ElMessage.success('活动创建成功')
        }
        
        // 跳转到活动列表
        router.push('/activity-list')
      } catch (error) {
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else if (error.name === 'Error') {
          // 验证失败的错误信息
          console.log('Validation error:', error)
        } else {
          ElMessage.error('操作失败，请重试')
        }
      } finally {
        submitting.value = false
      }
    }
    
    // 取消操作
    const handleCancel = () => {
      if (confirm('确定要取消编辑吗？未保存的内容将丢失。')) {
        router.push('/activity-list')
      }
    }
    
    // 头像上传成功处理
    const handleAvatarSuccess = (response) => {
      if (response.code === 200 && response.data) {
        activityForm.value.coverUrl = response.data.url
        ElMessage.success('上传成功')
      } else {
        ElMessage.error('上传失败')
      }
    }
    
    // 头像上传前校验
    const beforeAvatarUpload = (file) => {
      const isLt2M = file.size / 1024 / 1024 < 2
      const isImg = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
      
      if (!isImg) {
        ElMessage.error('只支持 jpg, png, gif 格式的图片')
        return false
      }
      
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB')
        return false
      }
      
      return true
    }
    
    // 初始化页面
    const initializePage = async () => {
      try {
        // 直接调用API获取分类列表
        const response = await getCategoryList()
        categories.value = response.data || []
        await fetchActivityDetail()
      } catch (err) {
        ElMessage.error('获取分类列表失败')
      }
    }
    
    // 获取映射后的状态
    const getMappedStatus = (status) => {
      return mapStatusToFrontend(status)
    }
    
    onMounted(async () => {
      await initializePage()
    })
    
    return {
      isEdit,
      activityFormRef,
      activityForm,
      activityRules,
      categories: computed(() => categories.value),
      submitting,
      loading,
      error,
      uploadUrl,
      handleSubmit,
      handleCancel,
      handleRetry,
      handleAvatarSuccess,
      beforeAvatarUpload,
      getMappedStatus
    }
  }
}
</script>

<style scoped>
.activity-edit-page {
  min-height: calc(100vh - 180px);
}

.breadcrumb {
  margin-bottom: 20px;
  padding: 10px 0;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.skeleton-container {
  padding: 20px 0;
}

.skeleton-container :deep(.el-skeleton-item) {
  margin-bottom: 16px;
}

.error-container {
  text-align: center;
  padding: 60px 20px;
}

.error-container .el-button {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 20px;
}

.editor-container {
  position: relative;
}

.editor-tip,
.upload-tip,
.form-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.avatar:hover {
  opacity: 0.9;
}

.avatar-uploader-icon {
  width: 200px;
  height: 150px;
  background: #f5f7fa;
  border: 1px dashed #c0c4cc;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28px;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-uploader-icon:hover {
  border-color: #409eff;
  color: #409eff;
}

.currency-unit {
  margin-left: 8px;
  color: #606266;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 40px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
}

@media (max-width: 768px) {
  .form-section {
    padding: 15px;
  }
  
  .avatar,
  .avatar-uploader-icon {
    width: 100%;
    max-width: 200px;
    height: auto;
    aspect-ratio: 4/3;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>